package com.hl.secondHand.shiro;

import com.hl.secondHand.entity.User;
import com.hl.secondHand.service.IUserService;
import com.hl.secondHand.util.JwtUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/*AccountProFile
    若token存在，会进入这里
 */
@Component  //注入spring
public class AccountRealm extends AuthorizingRealm {
    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    IUserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //在这里实际执行登录操作
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken token = (JwtToken) authenticationToken;
        String id = jwtUtil.getClaimByToken((String) token.getPrincipal()).getSubject();
        User user = userService.getById(id);
        if (user == null) {
            throw new UnknownAccountException("账户不存在");
        }
        //返回一些可公开的东西
        AccountProFile profile = new AccountProFile();  //封装一个返回对象的类
        BeanUtils.copyProperties(user, profile); //将user中一些相同的属性复制profile
        return new SimpleAuthenticationInfo(profile, token.getCredentials(), getName());  //返回身份信息、秘钥信息、realm的名字
    }

    @Override
    public boolean supports(AuthenticationToken token) {    //告诉他支持的是我定义的token，如果是就强转
        return token instanceof JwtToken;
    }
}
